package com.yksj.healthtalk.ui;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.friend.FriendSearchAboutZxingActivity;
import com.yksj.healthtalk.utils.PersonInfoUtil;

/**
 * 
 * 快捷搜索
 * @author zhao
 * 
 */
public class ShortcutSearchActivity extends BaseFragmentActivity implements OnClickListener {
	
	final int PAGE_SIZE = 10;//每页数量
	int mSearchType = 0;//查询类型
	int mCurrtnPage = 1;//当前页
	EditText mSearchEditText;
	TextView mQRCode;
	Button mButton;
	PullToRefreshListView mPullToRefreshListView;
	ResultListAdapter mAdapter;
	String mSearchTxt;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.shortcut_search_layout);
		
		if(arg0 != null){
			mSearchType = arg0.getInt("mSearchType");
		}else{
			mSearchType = getIntent().getIntExtra("type",0);
		}
		
		initUI();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("mSearchType", mSearchType);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.search_txtv://二维码扫描
			String type  = null;
			if(mSearchType == 1){
				type = "1";
			}else if(mSearchType == 4 || mSearchType == 5){
				type = "2";
			}else{
				type = "0";
			}
			Intent intent = new Intent();
			intent.setClass(this, FriendSearchAboutZxingActivity.class);
			intent.putExtra("type",type);// 0-社交场 1-医生馆 2 商户
			startActivity(intent);
			break;
		case R.id.seach_onclick:
			mSearchTxt = mSearchEditText.getEditableText().toString().trim();
			if(mSearchTxt.length() == 0) return;
			onSearchData(0);
			break;
		}
	}
	
	private void initUI(){
		initTitle();
		setBackBtn("返回",this);
		mQRCode = (TextView)findViewById(R.id.search_txtv);
		mQRCode.setOnClickListener(this);
		mButton = (Button)findViewById(R.id.seach_onclick);
		mButton.setOnClickListener(this);
		mButton.setText("确定");
		mSearchEditText = (EditText)findViewById(R.id.seach_text);
		findViewById(R.id.seach_onclick).setOnClickListener(this);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		
		if(mSearchType == 1){//查找医生
			mSearchEditText.setHint("请输入医生多美号码或者真实姓名");
			mQRCode.setText("扫描医生二维码");
			titleTextV.setText("查找医生");
			mAdapter = new ResultListAdapter(getLayoutInflater(),1);
		}else if(mSearchType == 2){//患者
			mSearchEditText.setHint("请输入患者多美号码或者昵称");
			mQRCode.setText("扫描患者二维码");
			titleTextV.setText("查找患者");
			mAdapter = new ResultListAdapter(getLayoutInflater(),2);
		}else if(mSearchType == 3){//朋友
			mSearchEditText.setHint("请输入朋友多美号码或者昵称");
			mQRCode.setText("扫描朋友二维码");
			titleTextV.setText("查找朋友");
			mAdapter = new ResultListAdapter(getLayoutInflater(),2);
		}/*else if(mSearchType == 4){//查找医院
			mSearchEditText.setHint("请输入医院名称");
			mQRCode.setText("扫描医院二维码");
		}else if(mSearchType == 5){//查找商家
			mSearchEditText.setHint("请输入商家名称");
			mQRCode.setText("扫描商家二维码");
		}*/else if(mSearchType == 6){//查找话题
			mQRCode.setVisibility(View.GONE);
			mSearchEditText.setHint("请输话题名称");
			titleTextV.setText("查找话题");
			mAdapter = new ResultListAdapter(getLayoutInflater(),3);
		}
		
		mPullToRefreshListView.setAdapter(mAdapter);
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener2() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
			}
			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				onSearchData(1);
			}
		});
	}
	
	/**
	 * 
	 * 总查询方法
	 * @param type  第一次0,刷新1;
	 * 
	 */
	private void onSearchData(int type){
		if(type == 0){//重新查找
			mAdapter.mArray.clear();
			mAdapter.notifyDataSetChanged();
			mCurrtnPage = 1;
		}
		if(mSearchType == 1){
			onSreachDoctors(type);
		}else{
			onSearchFriends(type);
		}
	}
	
	private void setEmptyView(String txt){
		TextView textView = new TextView(this);
		textView.setGravity(Gravity.CENTER);
		textView.setText(txt);
		mPullToRefreshListView.setEmptyView(textView);
	}
	
	/**
	 * 搜索医生
	 */
	private void onSreachDoctors(final int type){
		HttpRestClient.doHttpDoctorSearchResult(
				mSearchTxt, 
				SmartFoxClient.getLoginUserId(),
				mCurrtnPage,
				PAGE_SIZE,
				new ResultHttpResponseHandler(type,mSearchTxt));
	}
	
	/**
	 * 搜索朋友
	 */
	private void onSearchFriends(int type){
		HttpRestClient.doHttpFriendExactSearch(
				SmartFoxClient.getLoginUserId(),
				String.valueOf(mCurrtnPage),
				String.valueOf(PAGE_SIZE),
				mSearchTxt,
				0,
				new ResultHttpResponseHandler(type,mSearchTxt));
	}
	
	/**
	 * 请求结果
	 * @author zhao
	 *
	 */
	class ResultHttpResponseHandler extends JsonsfHttpResponseHandler{
		
		int mType = 0;
		String mSearcTxt;
		public ResultHttpResponseHandler(int type,String txt) {
			super(ShortcutSearchActivity.this);
			mType = type;
			mSearcTxt = txt;
		}
		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			if(response.containsKey("CUSLIST")){
				JSONArray array = response.getJSONArray("CUSLIST");
				if(array.size() != 0){
					mCurrtnPage++;
					mAdapter.onAddEndList(array);
				}
			}else if(response.containsKey("error_message") && mAdapter.getCount() == 0){
				setEmptyView(response.getString("error_message"));
			}
		}
		@Override
		public void onFinish() {
			super.onFinish();
			mPullToRefreshListView.onRefreshComplete();
			LodingFragmentDialog.dismiss(getSupportFragmentManager());
		}
	}
	
	
	/**
	 * 搜索结果
	 * @author zhao
	 */
	class ResultListAdapter extends BaseAdapter{
		JSONArray mArray = new JSONArray();
		private ImageLoader mImageLoader;
		private LayoutInflater mInflater;
		private int mType;
		
		public ResultListAdapter(LayoutInflater inflater,int type) {
			this.mType = type;
			mInflater = inflater;
			mImageLoader = ImageLoader.getInstance();
		}
		
		public void onAddEndList(JSONArray array){
			mArray.addAll(array);
			notifyDataSetChanged();
		}
		
		@Override
		public int getViewTypeCount() {
			return 5;
		}
		
		@Override
		public int getItemViewType(int position) {
			return mType;
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int  type = getItemViewType(position);
			if(convertView == null){
				convertView = onCeateView(type);
			}
			final ViewHolder holder = (ViewHolder)convertView.getTag();
			onBindView(holder, type, getItem(position));
			return convertView;
		}
		
		private View onCeateView(int typeView){
			ViewHolder mHolder = new ViewHolder();
			View convertView = null;
			switch(typeView){
			case 2:
				//好友
				convertView =  mInflater.inflate(R.layout.friendlist_item1,null);
				mHolder.headerImageView = (ImageView) convertView.findViewById(R.id.head_image);
				mHolder.nameTextView = (TextView) convertView.findViewById(R.id.name);
				mHolder.sexImageView = (ImageView)convertView.findViewById(R.id.head_sex);
				mHolder.levImageView = (ImageView) convertView.findViewById(R.id.levl);
				mHolder.noteTextView = (TextView) convertView.findViewById(R.id.note);
				break;
			case 1:
				//医生
				convertView = mInflater.inflate(R.layout.doctor_item1, null);
				mHolder.doctorVImageView = (ImageView) convertView.findViewById(R.id.v);
				mHolder.departmentsTextView = (TextView) convertView.findViewById(R.id.title_departments);
				mHolder.hospitalTextView = (TextView) convertView.findViewById(R.id.hospital);
				mHolder.specialTextView = (TextView) convertView.findViewById(R.id.special);
				mHolder.headerImageView = (ImageView) convertView.findViewById(R.id.head_image);
				mHolder.nameTextView = (TextView) convertView.findViewById(R.id.name);
				break;
			case 3://话题
				convertView = mInflater.inflate(R.layout.grouplist_item1,null);
				mHolder.headerImageView = (ImageView)convertView.findViewById(R.id.head_image);
				mHolder.msgTextView = (TextView)convertView.findViewById(R.id.item_dele);
				mHolder.nameTextView = (TextView)convertView.findViewById(R.id.name);
				mHolder.sexImageView = (ImageView)convertView.findViewById(R.id.doctor_salon);
				mHolder.levImageView = (ImageView)convertView.findViewById(R.id.levl);
				mHolder.noteTextView = (TextView)convertView.findViewById(R.id.note);
				mHolder.moneyImageView = (ImageView)convertView.findViewById(R.id.money);
				break;
			}
			convertView.setTag(mHolder);
			return convertView;
		}
		
		/**
		 * 绑定数据
		 * @param holder
		 * @param type
		 * @param jsonObject
		 * 
		 */
		private void onBindView(ViewHolder holder,int type,final JSONObject jsonObject){
			if(type == 1){//医生
				holder.nameTextView.setText(jsonObject.getString("customerNickname"));
				holder.specialTextView.setText(jsonObject.getString("doctorTitle")+"/"+jsonObject.getString("doctorSpecially"));
				holder.hospitalTextView.setText(jsonObject.getString("doctorHospital"));
				if(jsonObject.getString("doctorOffice2") != null && jsonObject.getString("doctorOffice2").length() != 0){
					holder.departmentsTextView.setText(jsonObject.getString("doctorOffice")+","+jsonObject.getString("doctorOffice2"));
				}else{
					holder.departmentsTextView.setText(jsonObject.getString("doctorOffice"));
				}
				mImageLoader.displayImage(jsonObject.getString("customerSex"),jsonObject.getString("clientIconBackground"),holder.headerImageView);
				holder.headerImageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						PersonInfoUtil.choiceActivity(jsonObject.getString("customerId"), ShortcutSearchActivity.this, jsonObject.getString("roleId"));
					}
				});
			}else if(type == 2){//好友
				String nickName = jsonObject.getString("customerNickname");
				if(nickName != null && nickName.length() !=0){
					holder.nameTextView.setText(nickName+"("+jsonObject.getString("customerAccounts")+")");
				}else{
					holder.nameTextView.setText(jsonObject.getString("customerAccounts"));
				}
				mImageLoader.displayImage(jsonObject.getString("customerSex"),jsonObject.getString("clientIconBackground"),holder.headerImageView);
				LevelListDrawable levelListDrawable = (LevelListDrawable)holder.sexImageView.getDrawable();
				levelListDrawable.setLevel(jsonObject.getIntValue("customerSex"));
				holder.headerImageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						PersonInfoUtil.choiceActivity(jsonObject.getString("customerId"), ShortcutSearchActivity.this, jsonObject.getString("roleId"));
					}
				});
			}else if(type == 3){//话题
				mImageLoader.displayImage("0",jsonObject.getString("clientIconBackground"),holder.headerImageView);
				holder.nameTextView.setText(jsonObject.getString("customerNickname"));
				holder.moneyImageView.setVisibility(jsonObject.getIntValue("chargingFlag") == 1?View.VISIBLE:View.GONE);
				((LevelListDrawable)holder.levImageView.getDrawable()).setLevel(jsonObject.getIntValue("groupLevel"));
				holder.sexImageView.setVisibility(jsonObject.getIntValue("groupClass") == 1?View.VISIBLE:View.GONE);
				holder.headerImageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						
					}
				});
			}
		}
	}
	
	static class ViewHolder{
		ImageView headerImageView;
		TextView  nameTextView;
		ImageView sexImageView;
		ImageView levImageView;
		TextView noteTextView;
		TextView departmentsTextView;
		TextView specialTextView;
		TextView hospitalTextView;
		ImageView doctorVImageView;
		ImageView moneyImageView;
		TextView msgTextView;
	}
	
}
